const authValidation = require('../units/auth');

module.exports = async (ctx, next) => {
    // 拦截器
    ctx.set({
        'Access-Control-Allow-Headers': 'Authorization, Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With',
        'Access-Control-Allow-Methods': 'PUT,PATCH,POST,GET,DELETE,OPTIONS',
        'Access-Control-Max-Age': '1728000',
        'Content-Type': 'application/json;charset=utf-8'
    });
    if (ctx.request.method === "OPTION") {
        ctx.status = 200;
        return false;
    }

    //白名单
    const isLogin = Object.is(ctx.request.url, "/api/login") && Object.is(ctx.request.method, 'POST');
    const isSetUserInfo = Object.is(ctx.request.url, "/api/setUserInfo") && Object.is(ctx.request.method, 'POST');
    if (isLogin || isSetUserInfo) {
        await next()
        return false;
    }
    if (! await authValidation.authToken(ctx.request)&&!Object.is(ctx.request.method,"GET")) {
        ctx.response.status = 401;
    }
    await next();
}